﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sy2_12
{
    public partial class Form1 : Form
    {
        double[] redPacketAmounts;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnDistribute_Click(object sender, EventArgs e)
        {
            try
            {
                // 解析输入的总金额和红包个数
                double totalAmount = double.Parse(txtTotalAmount.Text.Trim());
                int count = int.Parse(txtRedPacketCount.Text.Trim());

                // 输入合法性校验
                if (totalAmount <= 0 || count <= 0)
                {
                    MessageBox.Show("金额和个数必须为正数");
                    return;
                }
                if (totalAmount < count * 0.01)  // 确保每个红包至少0.01元
                {
                    MessageBox.Show("金额不足，无法分配（每个红包至少0.01元）");
                    return;
                }

                // 生成随机红包金额
                redPacketAmounts = new double[count];
                Random random = new Random();
                double remaining = totalAmount;  // 剩余金额

                // 前count-1个红包随机分配（保留2位小数）
                for (int i = 0; i < count - 1; i++)
                {
                    // 随机范围：[0.01, 剩余金额 - 0.01*(剩余个数-1)]
                    double max = remaining - 0.01 * (count - i - 1);
                    double amount = random.NextDouble() * (max - 0.01) + 0.01;
                    amount = Math.Round(amount, 2);  // 保留2位小数
                    redPacketAmounts[i] = amount;
                    remaining -= amount;
                }

                // 最后一个红包分配剩余金额（避免精度误差）
                redPacketAmounts[count - 1] = Math.Round(remaining, 2);

                // 显示红包金额
                string result = "分发红包：\n";
                for (int i = 0; i < count; i++)
                {
                    result += redPacketAmounts[i] + " ";
                    // 每5个换一行（优化显示）
                    if ((i + 1) % 5 == 0)
                        result += "\n";
                }
                txtRedPackets.Text = result;

                // 校验总和并显示
                double sum = 0;
                foreach (double amount in redPacketAmounts)
                {
                    sum += amount;
                }
                txtSum.Text = sum.ToString("0.00");  // 确保显示格式一致

            }
            catch (Exception ex)
            {
                MessageBox.Show("输入错误：" + ex.Message);
            }
        }
    }
}
